export default {
  formatDate: function (date, fmt) {
    if (/(y+)/.test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length))
    }
    let o = {
      'M+': date.getMonth() + 1,
      'd+': date.getDate(),
      'h+': date.getHours(),
      'm+': date.getMinutes(),
      's+': date.getSeconds()
    }
    for (let k in o) {
      if (new RegExp(`(${k})`).test(fmt)) {
        let str = o[k] + ''
        fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? str : padLeftZero(str))
      }
    }
    return fmt
  },
  getObjectURL: function (file) {
    var url = null
    if (window.createObjectURL !== undefined) { // basic
      url = window.createObjectURL(file)
    } else if (window.URL !== undefined) { // mozilla(firefox)
      url = window.URL.createObjectURL(file)
    } else if (window.webkitURL !== undefined) { // webkit or chrome
      url = window.webkitURL.createObjectURL(file)
    }
    return url
  },
  testFn: function () {
    console.log('asd')
  },
  isLogin: function (that, callback) {
    new Promise(function (resolve, reject) { // 第一步读取数据库条数 ，没有直接返回未登录
      that.$db.user_login.count({}, function (err, count) {
        if (err) reject(new Error('没有登录1'))
        resolve()
      })
    }).then(function () {
      return new Promise(function (resolve, reject) { // 第二步读取诗句哭里面id为0的数据  没有直接返回未登录
        that.$db.user_login.find({ id: 0 }, function (err, docs) {
          if (err) reject(new Error('没有登录2'))
          resolve(docs[0])
        })
      })
    }).then(function (doc) {
      // 第三步 数据库的token和userid传到服务器 验证登录状态
      var data = {
        user_id: doc.user.id,
        type: doc.type,
        key: doc.token
      }
      return that.$http.post(that.$store.state.node_url + '/isLogin', data)
    }).then(function (response) {
      if (response.data.status === 1) {
        callback(null, response.data)
        that.icp.send('show_main_window')
      } else {
        callback(new Error(response.data.msg), null)
      }
    }).catch(function (err) {
      callback(err, null)
    })
  },
  postLogin: function (that) {
    return that.$http.post(that.$store.state.node_url + '/login', {
      username: that.username,
      pwd: that.pwd,
      adminLogin: that.adminLogin,
      mobileLogin: that.mobileLogin,
      type: that.$store.state.login_type
    }).then(function (response) {
      var data = response.data
      return new Promise(function (resolve, reject) {
        if (data.status === 1) {
          var doc = {
            id: 0,
            user: data.user_info,
            token: data.key,
            type: that.$store.state.login_type
          }
          that.$db.user_login.remove({}, { multi: true }, function (err) {
            if (err) reject(new Error('调用数据库失败'))
            that.$db.user_login.insert(doc, function (err1, newDoc) {
              if (err1) reject(new Error('调用数据库失败'))
              resolve(newDoc)
            })
          })
        } else {
          reject(new Error(data.msg))
        }
      })
    })
  },
  getUserlist: function (that) { // 获取消息列表
    // 1，先从本地回去用户列表
    // 2. 获取线上用户合并到一起
    return new Promise(function (resolve, reject) {
      that.$db.user_list.find({ butt_id: that.user.user.id }, function (err, docs) {
      // that.$db.user_list.find({}, function (err, docs) {
        if (err) resolve([])
        resolve(docs)
      })
    }).then(function (docs) {
      // docs 本地数据库的用户
      // response 服务器的用户
      return new Promise(function (resolve, reject) {
        that.$http.post(that.$store.state.sever_url + '/User/autoPushMsg', {
          cs_id: that.user.user.id
        }).then(function (response) {
          var data = response.data.result
          var newdata = JSON.parse(JSON.stringify(data))
          docs.forEach(function (item, index) {
            data.forEach(function (item1, index1) {
              if (item1 && item.user_id === item1.user_id) {
                docs[index] = item1
                newdata[index1] = false
              }
            })
          })
          docs.push(...newdata) // 合并数组
          var arr = docs.filter(function (x) {
            return x
          })
          arr.forEach(function (item) {
            item.butt_id = that.user.user.id
          })
          that.$db.user_list.remove({butt_id: that.user.user.id}, { multi: true }, function (err, numRemoved) {
            if (err) reject(new Error('调用数据库失败'))
            that.$db.user_list.insert(arr, function (err1, newDocs) {
              if (err1) reject(new Error('调用数据库失败'))
              resolve(arr)
            })
          })
        }).catch(function (err) {
          if (err) console.log(err)
          resolve(docs)
        })
      })
    })
  },
  getLocaUser: function (that) { // 从本地回去客服信息
    return new Promise(function (resolve, reject) {
      that.$db.user_login.find({ id: 0 }, function (err, docs) {
        if (err) reject(new Error('调用数据库失败'))
        if (docs.length === 0) reject(new Error('还没有登录数据库没有'))
        resolve(docs[0])
      })
    })
  },
  setUsetType: function (that, type) { // 设置客服的在线状态
    return new Promise(function (resolve, reject) {
      var url = that.$store.state.sever_url + '/login/'
      if (type === 1) { // 设置为在线
        url += 'online'
      } else if (type === 2) {
        url += 'busy'
      } else if (type === 3) {
        url += 'outline'
      } else {
        reject(new Error('type参数错误'))
      }
      url = url + '?id=' + that.user.user.id
      that.$http.get(url).then(function (response) {
        if (response.data.status === 1) {
          resolve(response.data)
        } else {
          reject(response.data)
        }
      }).catch(function () {
        reject(new Error('接口请求失败'))
      })
    })
  },
  sendTextMsg: function (that, msg) { // 发送文本消息
    return that.$http.post(that.$store.state.sever_url + '/User/sengMsgForUser', msg)
  },
  sendImgMsg: function (that, msg) { // 发送图片消息
    let config = {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    }
    var formdata = new FormData()
    formdata.append('appid', msg.appid)
    formdata.append('openid', msg.openid)
    formdata.append('cs_id', msg.cs_id)
    formdata.append('image', msg.image)
    formdata.append('type', msg.type)
    formdata.append('send_time', msg.send_time)
    formdata.append('send_type', msg.send_type)
    return that.$http.post(that.$store.state.sever_url + '/User/sengImgForUser', formdata, config)
  },
  uploadMsgimg: function () { // 上传聊天图片
    return new Promise(function (resolve, reject) {
      var input = document.createElement('input')
      input.setAttribute('type', 'file')
      input.onchange = function () {
        var file = this.files[0]
        if (file.type !== 'image/jpeg' && file.type !== 'image/png' & file.type !== 'image/gif') { // 验证文件类型
          reject(new Error('文件类型不支持，只支持jpg，png，gif'))
        }
        if (file.size > 20971000) { // 验证文件大小
          reject(new Error('文件超出大小限制，只能上传20M一下的图片'))
        }
        resolve(file)
        input = null
      }
      input.click()
    })
  }
}

function padLeftZero (str) {
  return ('00' + str).substr(str.length)
}
